<template>
  <div>
    <Portlet title="" :show-title="true">
      <el-form :model="model" ref="form">
        <div class="col-xs-12" style="text-align: center; border-bottom: 1px dashed #C0CCDA;">
          <el-form-item
            prop="paymentType"
            :rules="[{required: true, message:'支付方式必须', trigger: 'change'}]"
          >
            <el-radio-group v-model="model.paymentType">
              <el-tooltip :key="index"  v-for="(item, index) in computedPaymentTypes" :disabled="!item.tip" :content='item.tip'>
                <el-radio-button :label="item.value" :disabled="item.disabled">
                  {{item.text}}
                </el-radio-button>
              </el-tooltip>
            </el-radio-group>
            <p>余额：{{balance | decimalNumFilter}} 元</p>
          </el-form-item>
        </div>
      </el-form>
      <div class="col-xs-12" style="text-align: center; margin-top: 15px;">
        <p>合并支付总计：<span style="color: red">{{moneyObj.totalMoney}}</span> 元
          <span style="margin-left: 30px">优惠减免总金额：<span style="color: red">{{moneyObj.totalDiscountMoney}}</span> 元</span>
          <span style="margin-left: 30px">实付支付总金额：<span style="color: red">{{moneyObj.totalActualMoney}}</span> 元</span>
        </p>
        <el-button style="margin-top: 15px" type="button" class="btn btn-primary btn-lg green ladda-button" data-style="zoom-out" :loading="btnLoading" @click="payment($event)">确认支付</el-button>
      </div>
      <div class="clearfix"></div>
    </Portlet>

    <el-dialog
      title="温馨提示"
      :visible.sync="paymentState"
      width="30%"
      center
    >
      <div style="text-align:center">恭喜您支付成功！本页面即将在3秒后跳转{{routeName === 'myOrdersPendingDetailPayment' ? '待付款' : '报价'}}列表</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnDialog">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="温馨提示"
      :visible.sync="payDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="30%"
      center
    >
      <div style="text-align:center" v-if="!disabledBtn">请您在新打开的页面完成支付?</div>
      <div style="text-align:center" v-if="disabledBtn">
        <b style="font-size: 16px;">订单支付状态暂时无法确认</b>
        <p>尊敬的客户你好，很抱歉我们暂时无法确认您的支付结果,<br>
          建议您等待五分钟后再查看支付结果</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!disabledBtn" @click="unsuccessful">支付遇到问题</el-button>
        <el-button type="primary" v-if="!disabledBtn" @click="successful" :disabled="disabledBtn">{{ disabledBtn ? '等待支付结果' : '已经完成支付' }}</el-button>
        <el-button type="primary" v-if="disabledBtn" @click="btnDialog"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="钱包密码"
      :visible.sync="showWalletPay"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="20%"
      center
    >
      <div style="text-align: center">
        <el-input v-model="walletPwd" type="password" :maxlength="6" />
        <span class="font-red">{{error_message}}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showWalletPay = false">取 消</el-button>
        <el-button type="primary" @click="walletpay" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
    <div v-html="htmltext"></div>
  </div>
</template>

<script>
import {dotData, alert, confirm} from '@/utils'
import {payFhbTypes} from '@/utils/selectOptions'
import {mapGetters} from 'vuex'
export default {
  name: 'paymentApprovePaymentPayment',
  props: {
    moneyObj: {
      type: Object,
      required: true
    },
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      // id: this.$route.params.id,
      idLen: 0,
      balance: 0,
      paymentTypes: [],
      model: {
        paymentType: ''
      },
      btnLoading: false,
      costLoading: null,
      orderDetail: [],
      // totalMoney: '',
      showWalletPay: false,
      walletPwd: '',
      htmltext: '',
      routeName: this.$route.name,
      routeNextPath: '/ss-fhb/paymentApprove/payment/index',
      paymentState: false,
      payDialog: false,
      disabledBtn: false,
      error_message: '',
      loading: false
    }
  },
  mounted() {
    this.getIdLen()
  },
  watch: {
    'moneyObj.totalMoney'(val, oldVal) {
      if (val === 0) {
        this.model.paymentType = '3'
      }
    }
  },
  computed: {
    cantWalletPay: function() {
      if (this.balance < parseFloat(this.moneyObj.totalActualMoney)) {
        return true
      } else {
        return false
      }
    },
    computedPaymentTypes() {
      return this.paymentTypes.map(v => {
        v = Object.assign({}, v)
        // 余额为零 禁用 支付宝微信
        if (this.lastMoney === 0) {
          if (['1', '2'].indexOf(v.value) >= 0) {
            v.disabled = true
          }
        }
        // 余额不足 禁用钱包余额
        if (this.cantWalletPay) {
          if (v.value === '3') {
            v.disabled = true
          }
        }

        // 配置禁用支付宝
        if (this.GET_GLOBAL_CONFIG('aliPayPC') === false) {
          console.log('aliPayPC', v.value)
          if (v.value === '1') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        // 配置禁用微信
        if (this.GET_GLOBAL_CONFIG('weChatPayPC') === false) {
          if (v.value === '2') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        // 配置禁用钱包余额
        if (this.GET_GLOBAL_CONFIG('walletPC') === false) {
          if (v.value === '3') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        return v
      })
    },
    ...mapGetters(['GET_GLOBAL_CONFIG'])
  },
  created() {
    // 支付方式
    this.createPaymentTypes()
    // 获取钱包余额
    this.$ajax.get('/ms-user-wallet/wallet/home-page').then(response => {
      let success = dotData(response, 'success')
      if (success) {
        this.balance = dotData(response, 'data.balance')
      }
    })
  },
  methods: {
    createPaymentTypes() {
      payFhbTypes().then(arr => {
        this.paymentTypes = arr
      })
    },
    payment($event) {
      // 钱包余额支付
      if (!this.model.paymentType) {
        alert('请选择支付方式')
        return
      }
      if (this.model.paymentType === '3') {
        this.showWalletPay = true
        this.walletPwd = ''
      } else {
        // 在线支付
        const newWindow = window.open('/static/pay.html')
        // let _this = this
        this.$refs.form.validate().then((result) => {
          if (result) {
            this.btnLoading = true
            this.$ajax.post('/ms-fahuobao-order/payPackage/paySM', {
              packageId: this.id,
              money: this.moneyObj.totalActualMoney,
              payType: this.model.paymentType,
              couponsOrderBeans: this.moneyObj.couponsOrderBeans
            }).then(response => {
              const success = dotData(response, 'success')
              if (success) {
                let temp = `<!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>Title</title>
                </head>
                <body>
                ${response.data.sHtmlText}
                </body>
                </html>
                `
                newWindow.document.write(temp)
                newWindow.focus()
                this.payDialog = true
                this.disablesdBtn = false
              } else {
                newWindow.close()
                this.unsuccessful()
              }
            }).catch(() => {
              newWindow.close()
              this.unsuccessful()
            })
          }
        })
      }
    },
    btnDialog() {
      this.paymentState = false
      this.$router.push({path: '/redirect/ss-fhb/paymentApprove/payment/index'})
    },
    successful() {
      // this.disabledBtn = true
      this.$ajax.get('/ms-fahuobao-order/payPackage/checkPay', {packageId: this.id}).then(response => {
        const success = dotData(response, 'data')
        if (success) {
          this.paymentState = true
          this.payDialog = false
          setTimeout(() => {
            this.btnDialog() // 刷新页面到父页面
          }, 3000)
        } else {
          this.disabledBtn = true
        }
      })
    },
    unsuccessful() {
      this.payDialog = false
      this.$confirm('很抱歉！支付失败。您可以尝试重新支付或联系客服。', '温馨提示', {
        confirmButtonText: '重新支付',
        cancelButtonText: '联系客服',
        closeOnClickModal: false,
        type: 'warning',
        center: true
      }).then(() => {
        // 重新支付
        // this.goPay()
        this.payment()
      }).catch(() => {
        // 联系客服
        this.btnLoading = false
      })
    },
    // 余额支付
    walletpay() {
      this.loading = true
      this.$ajax.post('/ms-fahuobao-order/pay-management/balance-pay-pay-management', {
        pageId: this.id,
        money: this.moneyObj.totalActualMoney,
        password: this.walletPwd,
        couponsOrderBeans: this.moneyObj.couponsOrderBeans
      }).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          confirm('支付成功', '提示', {
            type: 'success'
          }).finally(_ => {
            this.btnDialog() // 刷新页面到父页面
          })
          this.showWalletPay = false
          this.walletPwd = ''
        } else {
          this.error_message = dotData(response, 'error')
        }
        this.loading = false
      })
    },
    getIdLen() {
      if (this.id) {
        this.idLen = this.id.split(',').length
      }
    },
    show(data) {
    }
  }
}
</script>

<style scoped>

</style>
